<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import dayjs, { Dayjs } from 'dayjs';
import {
  Card,
  Form,
  Input,
  Select,
  DatePicker,
  Radio,
  InputNumber,
  Button,
  Space,
  message,
  Divider,
} from 'ant-design-vue';
import {
  createTaskApi,
  getTaskDetailApi,
  getTaskServiceTypesApi,
  updateTaskApi,
  type TaskApi,
} from '#/api';

const route = useRoute();
const router = useRouter();
const formRef = ref();
const saving = ref(false);
const publishing = ref(false);
const updating = ref(false);
const detailLoading = ref(false);
const LOCAL_STORAGE_KEY = 'tenant-task-publish-form';

const taskId = computed(() => {
  const queryValue = route.query.taskId;
  if (Array.isArray(queryValue)) {
    return queryValue[0] ?? '';
  }
  if (queryValue !== undefined) {
    return String(queryValue);
  }
  const paramValue = (route.params as Record<string, unknown> | undefined)?.id;
  return paramValue ? String(paramValue) : '';
});

const isEditMode = computed(() => Boolean(taskId.value));
const pageTitle = computed(() => (isEditMode.value ? '编辑任务' : '发布任务'));

const serviceTypeOptions = ref<string[]>([]);
const serviceTypeLoading = ref(false);
const settlementCycleOptions = [
  { label: '日', value: 'daily' },
  { label: '周', value: 'weekly' },
  { label: '月', value: 'monthly' },
];
const billingUnitOptions = ['日', '周', '月', '小时', '次', '个', '件'];
const genderOptions = [
  { label: '女', value: 'female' },
  { label: '男', value: 'male' },
  { label: '不限', value: 'unlimited' },
];
const educationOptions = [
  { label: '不限', value: 'unlimited' },
  { label: '初中', value: 'junior_high' },
  { label: '高中', value: 'high_school' },
  { label: '专科', value: 'college' },
  { label: '本科', value: 'bachelor' },
  { label: '硕士', value: 'master' },
  { label: '博士', value: 'doctor' },
];

interface TaskPublishForm {
  serviceType: string | undefined;
  name: string;
  dateRange: Dayjs[];
  settlementCycle: string;
  minFee: number | null;
  maxFee: number | null;
  feeUnit: string;
  genderRequirement: string;
  educationRequirement: string;
  minAge: number;
  maxAge: number;
  workLocation: string;
  workContent: string;
  workCompensation: string;
  workTime: string;
  workBenefits: string;
}

const formState = reactive<TaskPublishForm>({
  serviceType: undefined,
  name: '',
  dateRange: [],
  settlementCycle: 'daily',
  minFee: null,
  maxFee: null,
  feeUnit: '日',
  genderRequirement: 'unlimited',
  educationRequirement: 'unlimited',
  minAge: 18,
  maxAge: 65,
  workLocation: '',
  workContent: '',
  workCompensation: '',
  workTime: '',
  workBenefits: '',
});

const resetFormToDefault = () => {
  formState.serviceType = undefined;
  formState.name = '';
  formState.dateRange = [];
  formState.settlementCycle = 'daily';
  formState.minFee = null;
  formState.maxFee = null;
  formState.feeUnit = '日';
  formState.genderRequirement = 'unlimited';
  formState.educationRequirement = 'unlimited';
  formState.minAge = 18;
  formState.maxAge = 65;
  formState.workLocation = '';
  formState.workContent = '';
  formState.workCompensation = '';
  formState.workTime = '';
  formState.workBenefits = '';
};

const rules = {
  serviceType: [{ required: true, message: '请选择服务类型' }],
  name: [
    { required: true, message: '请输入任务名称' },
    { max: 32, message: '任务名称最多32个字符', trigger: 'change' },
  ],
  dateRange: [
    { required: true, type: 'array', min: 2, message: '请选择任务周期' },
  ],
  settlementCycle: [{ required: true, message: '请选择结算周期' }],
  minFee: [
    { required: true, message: '请输入最低计费' },
    {
      validator: (_: unknown, value: number) => {
        if (value === undefined || value === null) {
          return Promise.reject('请输入最低计费');
        }
        if (value < 0) {
          return Promise.reject('计费金额不能小于0');
        }
        if (formState.maxFee !== null && value > formState.maxFee) {
          return Promise.reject('最低计费不能大于最高计费');
        }
        return Promise.resolve();
      },
      trigger: 'change',
    },
  ],
  maxFee: [
    { required: true, message: '请输入最高计费' },
    {
      validator: (_: unknown, value: number) => {
        if (value === undefined || value === null) {
          return Promise.reject('请输入最高计费');
        }
        if (value < 0) {
          return Promise.reject('计费金额不能小于0');
        }
        if (formState.minFee !== null && value < formState.minFee) {
          return Promise.reject('最高计费不能小于最低计费');
        }
        return Promise.resolve();
      },
      trigger: 'change',
    },
  ],
  feeUnit: [{ required: true, message: '请选择计费单位' }],
  genderRequirement: [{ required: true, message: '请选择性别要求' }],
  educationRequirement: [{ required: true, message: '请选择学历要求' }],
  minAge: [
    { required: true, message: '请输入最低年龄' },
    {
      validator: (_: unknown, value: number) => {
        if (value === undefined || value === null) {
          return Promise.reject('请输入最低年龄');
        }
        if (value < 16) {
          return Promise.reject('最低年龄不能小于16岁');
        }
        if (formState.maxAge && value > formState.maxAge) {
          return Promise.reject('最低年龄不能大于最高年龄');
        }
        return Promise.resolve();
      },
      trigger: 'change',
    },
  ],
  maxAge: [
    { required: true, message: '请输入最高年龄' },
    {
      validator: (_: unknown, value: number) => {
        if (value === undefined || value === null) {
          return Promise.reject('请输入最高年龄');
        }
        if (value > 100) {
          return Promise.reject('最高年龄不能超过100岁');
        }
        if (formState.minAge && value < formState.minAge) {
          return Promise.reject('最高年龄不能小于最低年龄');
        }
        return Promise.resolve();
      },
      trigger: 'change',
    },
  ],
  workLocation: [{ required: true, message: '请输入工作地点' }],
  workContent: [{ required: true, message: '请输入工作内容' }],
  workCompensation: [{ required: true, message: '请输入佣金说明' }],
  workTime: [{ required: true, message: '请输入工作时间' }],
};

const ensureServiceTypeSelectable = () => {
  if (!formState.serviceType) {
    return;
  }
  if (!serviceTypeOptions.value.includes(formState.serviceType)) {
    serviceTypeOptions.value = [...serviceTypeOptions.value, formState.serviceType];
  }
};

const fetchServiceTypeOptions = async () => {
  serviceTypeLoading.value = true;
  try {
    const response = await getTaskServiceTypesApi();
    const names = Array.isArray(response) ? response.map((item) => item.name).filter(Boolean) : [];
    serviceTypeOptions.value = names;
  } catch (error) {
    console.error('获取服务类型失败', error);
    message.warning('获取服务类型失败');
    serviceTypeOptions.value = [];
  } finally {
    serviceTypeLoading.value = false;
    ensureServiceTypeSelectable();
  }
};

const saveToLocal = () => {
  const payload = {
    ...formState,
    dateRange: formState.dateRange.map((item) => (item ? item.format('YYYY-MM-DD') : null)),
  };
  localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(payload));
};

const handleSaveDraft = async () => {
  try {
    saving.value = true;
    saveToLocal();
    message.success('已将内容保存到本地');
  } finally {
    saving.value = false;
  }
};

const buildPayload = () => {
  const [start, end] = formState.dateRange;
  if (!start || !end) {
    throw new Error('任务周期不完整');
  }
  if (!formState.serviceType) {
    throw new Error('请选择服务类型');
  }
  if (formState.minFee === null || formState.maxFee === null) {
    throw new Error('请完善计费信息');
  }
  return {
    service_type: formState.serviceType,
    name: formState.name.trim(),
    start_time: start.format('YYYY-MM-DD'),
    end_time: end.format('YYYY-MM-DD'),
    settlement_cycle: formState.settlementCycle,
    min_fee: Number(formState.minFee),
    max_fee: Number(formState.maxFee),
    billing_unit: formState.feeUnit,
    gender_requirement: formState.genderRequirement,
    education_requirement: formState.educationRequirement,
    min_age: formState.minAge,
    max_age: formState.maxAge,
    work_location: formState.workLocation,
    work_content: formState.workContent,
    work_compensation: formState.workCompensation,
    work_time: formState.workTime,
    work_benefits: formState.workBenefits || null,
  };
};

const handlePublish = async () => {
  if (!formRef.value) return;
  try {
    publishing.value = true;
    await formRef.value.validate();
    if (!formState.dateRange || formState.dateRange.length < 2) {
      message.error('请选择任务周期');
      return;
    }
    const payload = buildPayload();
    await createTaskApi(payload);
    message.success('任务发布成功');
    localStorage.removeItem(LOCAL_STORAGE_KEY);
    router.push({ name: 'TaskCenter' });
  } catch (error: any) {
    if (error?.errorFields) {
      message.error('请检查表单填写是否完整');
    } else {
      message.error(error?.message || '任务发布失败，请稍后重试');
    }
  } finally {
    publishing.value = false;
  }
};

const handleCancel = () => {
  router.back();
};

const populateFormFromTask = (task: TaskApi.TaskRecord) => {
  resetFormToDefault();
  formState.serviceType = task.service_type || undefined;
  ensureServiceTypeSelectable();
  formState.name = task.name || '';
  formState.dateRange = [dayjs(task.start_time), dayjs(task.end_time)] as Dayjs[];
  formState.settlementCycle = task.settlement_cycle || 'daily';
  formState.minFee = task.min_fee !== undefined && task.min_fee !== null ? Number(task.min_fee) : null;
  formState.maxFee = task.max_fee !== undefined && task.max_fee !== null ? Number(task.max_fee) : null;
  formState.feeUnit = task.billing_unit || '日';
  formState.genderRequirement = task.gender_requirement || 'unlimited';
  formState.educationRequirement = task.education_requirement || 'unlimited';
  formState.minAge = task.min_age ?? 18;
  formState.maxAge = task.max_age ?? 65;
  formState.workLocation = task.work_location || '';
  formState.workContent = task.work_content || '';
  formState.workCompensation = task.work_compensation || '';
  formState.workTime = task.work_time || '';
  formState.workBenefits = task.work_benefits || '';
};

const fetchTaskDetail = async () => {
  if (!taskId.value) {
    return;
  }
  detailLoading.value = true;
  try {
    const task = await getTaskDetailApi(taskId.value);
    populateFormFromTask(task);
  } catch (error) {
    console.error('获取任务详情失败', error);
    message.error('获取任务详情失败，请稍后重试');
    router.push({ name: 'TaskCenter' });
  } finally {
    detailLoading.value = false;
  }
};

const restoreFromLocal = () => {
  const cache = localStorage.getItem(LOCAL_STORAGE_KEY);
  if (!cache) return;
  try {
    resetFormToDefault();
    const parsed = JSON.parse(cache);
    formState.serviceType = parsed.serviceType ?? undefined;
    formState.name = parsed.name ?? '';
    if (Array.isArray(parsed.dateRange) && parsed.dateRange.length === 2) {
      formState.dateRange = parsed.dateRange.map((item: string | null) => (item ? dayjs(item) : null)).filter(Boolean) as Dayjs[];
    } else {
      formState.dateRange = [];
    }
    formState.settlementCycle = parsed.settlementCycle ?? 'daily';
    formState.minFee = parsed.minFee ?? null;
    formState.maxFee = parsed.maxFee ?? null;
    formState.feeUnit = parsed.feeUnit ?? '日';
    formState.genderRequirement = parsed.genderRequirement ?? 'unlimited';
    formState.educationRequirement = parsed.educationRequirement ?? 'unlimited';
    formState.minAge = parsed.minAge ?? 18;
    formState.maxAge = parsed.maxAge ?? 65;
    formState.workLocation = parsed.workLocation ?? '';
    formState.workContent = parsed.workContent ?? '';
    formState.workCompensation = parsed.workCompensation ?? '';
    formState.workTime = parsed.workTime ?? '';
    formState.workBenefits = parsed.workBenefits ?? '';
    ensureServiceTypeSelectable();
  } catch (e) {
    console.warn('恢复草稿失败', e);
  }
};

onMounted(async () => {
  await fetchServiceTypeOptions();
  if (isEditMode.value) {
    await fetchTaskDetail();
  } else {
    resetFormToDefault();
    restoreFromLocal();
  }
});

watch(
  () => taskId.value,
  async (newId, oldId) => {
    if (newId && newId !== oldId) {
      if (!serviceTypeOptions.value.length) {
        await fetchServiceTypeOptions();
      }
      await fetchTaskDetail();
    }
    if (!newId && !isEditMode.value) {
      resetFormToDefault();
      restoreFromLocal();
    }
  },
);

const handleUpdate = async () => {
  if (!formRef.value || !taskId.value) {
    return;
  }
  try {
    updating.value = true;
    await formRef.value.validate();
    if (!formState.dateRange || formState.dateRange.length < 2) {
      message.error('请选择任务周期');
      return;
    }
    const payload = buildPayload();
    await updateTaskApi(taskId.value, payload);
    message.success('任务更新成功');
    router.push({ name: 'TaskCenter' });
  } catch (error: any) {
    if (error?.errorFields) {
      message.error('请检查表单填写是否完整');
    } else {
      message.error(error?.message || '任务更新失败，请稍后重试');
    }
  } finally {
    updating.value = false;
  }
};
</script>

<template>
  <div class="p-5">
    <Card :title="pageTitle" :loading="isEditMode ? detailLoading : false">
      <Form ref="formRef" :model="formState" :rules="rules" layout="vertical">
        <Divider orientation="left">基本信息</Divider>
        <div class="grid gap-6 md:grid-cols-2">
          <Form.Item label="服务类型" name="serviceType">
            <Select
              v-model:value="formState.serviceType"
              placeholder="请选择服务类型"
              :options="serviceTypeOptions.map((item) => ({ label: item, value: item }))"
              :loading="serviceTypeLoading"
              allow-clear
            />
          </Form.Item>
          <Form.Item label="任务名称" name="name">
            <Input v-model:value="formState.name" placeholder="请输入任务名称" :maxlength="32" />
          </Form.Item>
          <Form.Item label="任务周期" name="dateRange">
            <DatePicker.RangePicker
              v-model:value="formState.dateRange"
              style="width: 100%"
              format="YYYY-MM-DD"
            />
          </Form.Item>
          <Form.Item label="结算周期" name="settlementCycle">
            <Radio.Group v-model:value="formState.settlementCycle">
              <Radio.Button
                v-for="item in settlementCycleOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="任务计费" required>
            <Space>
              <Form.Item name="minFee" no-style>
                <InputNumber
                  v-model:value="formState.minFee"
                  :min="0"
                  :precision="2"
                  placeholder="最低计费"
                  style="width: 140px"
                />
              </Form.Item>
              <span>~</span>
              <Form.Item name="maxFee" no-style>
                <InputNumber
                  v-model:value="formState.maxFee"
                  :min="0"
                  :precision="2"
                  placeholder="最高计费"
                  style="width: 140px"
                />
              </Form.Item>
              <span>元/</span>
              <Form.Item name="feeUnit" no-style>
                <Select
                  v-model:value="formState.feeUnit"
                  style="width: 120px"
                  :options="billingUnitOptions.map((item) => ({ label: item, value: item }))"
                />
              </Form.Item>
            </Space>
          </Form.Item>
        </div>

        <Divider orientation="left">简历要求</Divider>
        <div class="grid gap-6 md:grid-cols-2">
          <Form.Item label="性别" name="genderRequirement">
            <Radio.Group v-model:value="formState.genderRequirement">
              <Radio.Button v-for="item in genderOptions" :key="item.value" :value="item.value">
                {{ item.label }}
              </Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="学历" name="educationRequirement">
            <Radio.Group v-model:value="formState.educationRequirement">
              <Radio.Button
                v-for="item in educationOptions"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="年龄" required>
            <Space>
              <Form.Item name="minAge" no-style>
                <InputNumber
                  v-model:value="formState.minAge"
                  :min="16"
                  :max="100"
                  placeholder="最低年龄"
                />
              </Form.Item>
              <span>岁 ~</span>
              <Form.Item name="maxAge" no-style>
                <InputNumber
                  v-model:value="formState.maxAge"
                  :min="16"
                  :max="100"
                  placeholder="最高年龄"
                />
              </Form.Item>
              <span>岁</span>
            </Space>
          </Form.Item>
        </div>

        <Divider orientation="left">任务详情</Divider>
        <Form.Item label="工作地点" name="workLocation">
          <Input v-model:value="formState.workLocation" placeholder="请输入工作地点" />
        </Form.Item>
        <Form.Item label="工作内容" name="workContent">
          <Input.TextArea
            v-model:value="formState.workContent"
            placeholder="请输入工作内容"
            :rows="4"
            :maxlength="500"
            show-count
          />
        </Form.Item>
        <Form.Item label="佣金说明" name="workCompensation">
          <Input.TextArea
            v-model:value="formState.workCompensation"
            placeholder="请输入佣金说明"
            :rows="3"
            :maxlength="500"
            show-count
          />
        </Form.Item>
        <Form.Item label="工作时间" name="workTime">
          <Input.TextArea
            v-model:value="formState.workTime"
            placeholder="请输入工作时间"
            :rows="3"
            :maxlength="300"
            show-count
          />
        </Form.Item>
        <Form.Item label="其他福利" name="workBenefits">
          <Input.TextArea
            v-model:value="formState.workBenefits"
            placeholder="请输入其他福利 (选填)"
            :rows="3"
            :maxlength="300"
            show-count
          />
        </Form.Item>

        <Form.Item>
          <Space>
            <Button v-if="!isEditMode" @click="handleSaveDraft" :loading="saving">保存</Button>
            <Button
              v-if="!isEditMode"
              type="primary"
              @click="handlePublish"
              :loading="publishing"
            >
              发布
            </Button>
            <Button
              v-else
              type="primary"
              @click="handleUpdate"
              :loading="updating"
            >
              更新
            </Button>
            <Button @click="handleCancel">取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  </div>
</template>
